<?php
	header('Content-Type: text/html; charset=utf-8');

    class System{
    	
    	//Variáveis globais do moodle
    	var $USER;    	
    	var $SESSION;    	
    	var $CFG;    	
    	var $DB;
    	
    	//Dado serializado da sessao
    	var $srv_data;
    	
    	//Contexto do curso
    	var $context;
    	
    	//Cursos do usuario
    	var $user_courses;
    	
    	//Curso acessado
    	var $course;
    	
    	//Perfils de tutor
    	var $manager_roles;
    	
    	//Perfil de estudante
    	var $student_role;
    	
    	//Usuários professores
    	var $manager_users;
    	
    	//Usuários estudantes
    	var $student_users;
    	
    	//Perfil
    	var $perfil;
    	
    	//Permissao
    	var $permission;
    	
        private $_url;
        private $_explode;
        public $_controller;
        public $_action;
        public $_params;
        
        public function  __construct(){        	
        	
        	global $USER, $SESSION, $CFG, $DB;
        	
        	$this->USER = $USER;
        	$this->SESSION = $SESSION;
        	$this->CFG = $CFG;
        	$this->DB = $DB;
        	
        	$this->srv_data = $this->get_srv_data();
        	$this->context = $this->get_context_course();
        	$this->user_courses = $this->get_courses_user();
        	$this->course = $this->get_course();
        	$this->manager_roles = $this->get_manager_roles();
        	$this->student_role = $this->get_student_role();
        	$this->manager_users = $this->get_manager_users();
        	$this->student_users = $this->get_student_users();
        	
        	$this->check_course();
        	$this->setPermission();
        	
            $this->setUrl();
            $this->setExplode();
            $this->setController();
            $this->setAction();
            $this->setParams();
            
        }
        
        //get srv_data
        protected function get_srv_data(){     
			
        	if($this->SESSION->srv_data_encoded)
        		return (object) unserialize(base64_decode(urldecode($this->SESSION->srv_data_encoded)));
        	else
        		notice('Sessão experiou. Efetue login novamente.', '/');
        	
        }
        
        //get context
        protected function get_context_course(){
        	
        	if ($this->srv_data->context) 
        		return $this->srv_data->context;
        	else
        		notice('Nenhum contexto de curso encontrado.', '/');
        	
        }
        
        //get courses for users
        protected function get_courses_user(){
        	
        	if ($userCourses = enrol_get_users_courses($this->USER->id, true))        		
        		return $userCourses;
        	else
        		notice('Você não está inserido em nenhum curso.', '/');
        	
        }
        
        //get course
        protected function get_course(){

        	if ($course = $this->DB->get_record("course", array('id'=>$this->srv_data->course_id)))
				return $course;
			else
				notice('Nenhum curso encontrado.', '/');

        }
        
        //get manager roles
        protected function get_manager_roles(){
        	
        	if($managerroles = explode(',', $this->srv_data->coursecontact))
        		return $managerroles;
			else
        		notice('Não existe perfil de tutor na plataforma.', '/');
        	
        }
        
        //get student role
        protected function get_student_role(){
        	
        	if($studentrole = $this->DB->get_record("role", array('archetype'=>'student')))
        		return $studentrole;
        	else
        		notice('Não existe perfil de estudante na plataforma.', '/');

        }
        
        //get manager users
        protected function get_manager_users(){
        	
        	if($rusers = get_role_users($this->manager_roles, $this->context, true, '', 'u.firstname ASC'))
        		return $rusers;
        	else	
        		notice('O curso não possui tutor.', '/');
        	
        }
        
        //get student users
        protected function get_student_users(){
        
        	return get_role_users($this->student_role->id, $this->context, true, '', 'u.firstname ASC');
        
        }
        
        //Verifica se o curso acessado pertence a gama de cursos do usuário
        protected function check_course(){        	
        	if ($this->user_courses[$this->course->id]->id != $this->course->id)
        		notice('Você não está inserido neste curso.', '/');
        	else
        		return true;
        }
        
        //Set permissions
        private function setPermission(){
        	
        	foreach ($this->student_users as $student){
        		if($student->id == $this->USER->id){
        			$this->SESSION->profile = 'student';
        			$this->permission = array('pages/index', 'pages/guide', 'pages/about', 'units/index', 'units/vision', 'exams/index', 'exams/answers', 'history/index', 'history/exams', 'history/questions');
        			break;
        		}
        	}
        	
        	foreach ($this->manager_users as $teacher){
        		if($teacher->id == $this->USER->id){
        			$this->SESSION->profile = 'teacher';
        			$this->permission = array('pages/index', 'pages/guide', 'pages/about', 'units/add', 'units/index', 'units/edit', 'units/vision', 'follow/index', 'follow/log','follow/units', 'follow/exams', 'follow/questions', 'questions/index', 'questions/add', 'questions/visualize', 'exams/index', 'exams/answers');
        			break;
        		}
        	}
        	
        }

        private function setUrl(){
            $_GET['url'] = (isset($_GET['url']) ? $_GET['url'] : 'pages/index_action');
            $this->_url = $_GET['url'] .'/' ;
        }

        private function setExplode(){
            $this->_explode = explode( '/' , $this->_url );
        }

        private function setController(){
            $this->_controller = $this->_explode[0];
        }
        
        private function setAction(){
            $ac = (!isset($this->_explode[1]) || $this->_explode[1] == null || $this->_explode[1] == 'index' ? 'index_action' : $this->_explode[1]);
            $this->_action = $ac;
        }

        private function setParams(){
            unset( $this->_explode[0], $this->_explode[1] );
            array_pop( $this->_explode );

            if ( end( $this->_explode ) == null )
                array_pop( $this->_explode );

            $i = 0;
            if( !empty ($this->_explode) ){
                foreach ( $this->_explode as $val ){
                    if ( $i % 2 == 0 ){
                        $ind[] = $val;
                    }else{
                        $value[] = $val;
                    }
                    $i++;
                }
            }else{
                $ind = array();
                $value = array();
            }
            if( count($ind) == count($value) && !empty($ind) && !empty($value) )
                $this->_params = array_combine($ind, $value);
            else
                $this->_params = array();
        }

        public function getParam( $name = null ){
            if ( $name != null )
                return $this->_params[$name];
            else
                return $this->_params;
        }

        public function run(){
            $controller_path = CONTROLLERS . $this->_controller . 'Controller.php';
                        
            if( !file_exists( $controller_path ) )
                notice('O endereço que você acessou não existe.', '/blocks/oaeditor/');

            require_once( $controller_path );
            $app = new $this->_controller();

			if( !method_exists($app, $this->_action) )
				notice('O endereço que você acessou não existe.', '/blocks/oaeditor/');

            $action = $this->_action;
            $app->$action();
        }
    }